<template>
  <div class="PointsEdit">
    <el-dialog
      custom-class="el-dialog-redefine"
      v-bind="$attrs"
      title="点位关系"
      :visible.sync="dialogVisible"
      :show-close="showClose"
      @open="dialogOpen"
    >
      <div class="outside-border">
        <div class="data-area">
          <el-tabs class="el-tabs-redefine" v-model="editableTabsValue" type="border-card">
            <el-tab-pane label="三相对比" name="first" v-if="nType === 3">
              <div class="tab-custom-area">
                <div class="tip-info" v-if="bValid === 1">绑定条件不成立！</div>
                <div class="conditions-area" v-else-if="bValid === 2">
                  <el-form
                    ref="TDifferenceFormRules"
                    :model="TDifferenceForm"
                    :rules="TDifferenceFormRules"
                    size="mini"
                    label-width="150px"
                  >
                    <el-row v-for="item in TDifferenceDataList" :key="item.pointId">
                      <el-col :span="8">
                        <el-form-item size="mini" label="点位名称:">
                          <el-select size="mini" placeholder="请选择" v-model="item.pointId">
                            <el-option
                              v-for="itemChild in pointsList.filter(it => it.id == item.pointId)"
                              :key="itemChild.id"
                              :label="itemChild.name"
                              :value="itemChild.id"
                              disabled
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col
                        :span="8"
                        v-for="relationItem in item.relationPoint"
                        :key="relationItem.pointId"
                      >
                        <el-form-item size="mini" label="关联点:">
                          <el-select
                            size="mini"
                            placeholder="请选择"
                            v-model="relationItem.pointId"
                            @change="abcdefa"
                          >
                            <el-option
                              v-for="item in item.pointsList"
                              :key="item.id"
                              :label="item.name"
                              :value="item.id"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="三相温差" name="second" v-if="nType === 4">
              <div class="tab-custom-area">
                <div class="tip-info" v-if="bValid === 1">绑定条件不成立！</div>
                <div class="conditions-area" v-else-if="bValid === 2">
                  <el-form
                    ref="contrastForm"
                    :model="contrastForm"
                    :rules="contrastFormRules"
                    size="mini"
                    label-width="150px"
                  >
                    <el-row v-for="item in contrastDataList" :key="item.pointId">
                      <el-col :span="8">
                        <el-form-item size="mini" label="点位名称:">
                          <el-select size="mini" placeholder="请选择" v-model="item.pointId">
                            <el-option
                              v-for="item in pointsList.filter(it => it.id == item.pointId)"
                              :key="item.id"
                              :label="item.name"
                              :value="item.id"
                              disabled
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col
                        :span="8"
                        v-for="relationItem in item.relationPoint"
                        :key="relationItem.pointId"
                      >
                        <el-form-item size="mini" label="关联点:">
                          <el-select size="mini" placeholder="请选择" v-model="relationItem.pointId">
                            <el-option
                              v-for="item in pointsList.filter(it => it.id == relationItem.pointId)"
                              :key="item.id"
                              :label="item.name"
                              :value="item.id"
                              disabled
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <el-button
          v-if="!bExistence"
          :disabled="!bValid"
          size="small"
          style="width: 130px; margin: 10px 0; float: right;"
          @click="saveClick(true)"
        >保存</el-button>
        <el-button
          v-if="bExistence"
          size="small"
          style="width: 130px; margin: 10px 0; float: right;"
          @click="saveClick(false)"
        >解绑</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  pointsList,
  pointRelationSettingsList,
  pointRelationSettingsRelationsList,
  pointRelationSettingsUpdate,
  robotParams,
  postOperationLogs
} from "@/api/apiManagement";
import { validatEmpty } from "@/utils/validate";
import { format } from "path";
import { fail } from "assert";

export default {
  name: "PointsEdit",
  props: {
    showClose: {
      type: Boolean,
      default: true
    },
    data: {
      type: [Array, Object],
      required: true
    },
    pointListData: {
      type: [Array],
      required: true
    }
  },
  data() {
    return {
      robot_id: null,
      dialogVisible: false,
      editableTabsValue: "first",
      isEdit: false,
      nType: 0,
      bValid: 0,
      bExistence: false,
      pointsList: [],
      TDifferenceDataList: [],
      contrastDataList: [],
      TDifferenceForm: {},
      TDifferenceFormRules: {},
      contrastForm: {},
      contrastFormRules: {},
      rosObj: {
        ip: "",
        port: ""
      },
      comparedFilter: []
    };
  },
  computed: {},
  created() {
    // this.pointsList = this.pointListData;
  },
  mounted() {},
  methods: {
    isShowDia(isVisible, bEdit, type) {
      let self = this;
      self.dialogVisible = isVisible;
      self.isEdit = bEdit;
      self.nType = type;
    },
    dialogOpen() {
      this.pointsList = this.pointListData;
      this.robot_id = localStorage.getItem("ydRobot_id");
      this.getRobotParams({
        page: 1,
        size: 0,
        robotId: this.robot_id,
        type: 3
      });
      this.bValid = 0;
      this.bExistence = false;
      this.TDifferenceDataList = [];
      this.contrastDataList = [];
      this.comparedFilter = [];
      if (this.nType === 3) {
        this.editableTabsValue = "first";
      }
      if (this.nType === 4) {
        this.editableTabsValue = "second";
      }

      this.setData();
      // this.getPointsList();
      //
      // if (this.isEdit) {
      // } else {
      //   //
      // }
    },
    setData() {
      if (this.data && this.data.id) {
        let pointId = this.data.id.substring(6, this.data.id.length);
        let tempType = 0;
        if (this.nType == 3) {
          tempType = 1;
        }
        if (this.nType == 4) {
          tempType = 0;
        }
        this.getPointRelationSettingsList(
          {
            page: 1,
            size: 0,
            pointIds: pointId,
            type: tempType
          },
          res => {
            this.bValid = 1;
            if (this.nType === 3) {
              if (
                res &&
                res.list &&
                res.list.length > 0 &&
                res.list[0].dependPoint &&
                res.list[0].dependPoint.length > 0
              ) {
                this.bValid = 2;
                this.bExistence = true;
                let tempList = JSON.parse(res.list[0].dependPoint);
                if (tempList.pointRelationSettingRequests.length > 0) {
                  this.TDifferenceDataList = this.initTDifferenceData(
                    tempList.pointRelationSettingRequests
                  );
                }
              } else {
                var arr = this.searchTDifferenceData();

                var is_exist = true;
                arr.forEach(item => {
                  if (
                    item.relationPointIds &&
                    item.relationPointIds.length > 0
                  ) {
                    // 逗
                  } else {
                    is_exist = false;
                    this.bValid = 1;
                  }
                });
                if (is_exist === false) return;
                this.TDifferenceDataList = this.initTDifferenceData(arr);
                if (this.TDifferenceDataList.length >= 3) {
                  this.bValid = 2;
                }
              }
            }
            if (this.nType === 4) {
              if (
                res &&
                res.list &&
                res.list.length > 0 &&
                res.list[0].dependPoint &&
                res.list[0].dependPoint.length > 0
              ) {
                this.bValid = 2;
                this.bExistence = true;
                let tempList = JSON.parse(res.list[0].dependPoint);
                if (tempList.pointRelationSettingRequests.length > 0) {
                  this.contrastDataList = this.initContrastData(
                    tempList.pointRelationSettingRequests
                  );
                }
              } else {
                var arr = this.searchContrastData();
                this.contrastDataList = this.initContrastData(arr);
                if (this.contrastDataList.length >= 3) {
                  this.bValid = 2;
                }
              }
            }
          }
        );
        // //
        // if (this.nType === 3) {
        //   var arrPoints = this.searchTDifferenceData();
        //   let pointIds = arrPoints
        //     .map(item => {
        //       return item.pointId;
        //     })
        //     .join(",");
        //   this.getPointRelationSettingsList(
        //     {
        //       page: 1,
        //       size: 0,
        //       pointIds: pointIds,
        //       type: 1
        //     },
        //     res => {
        //       if (this.nType === 3) {
        //         if (res && res.list && res.list.length > 0) {
        //           this.bValid = true;
        //           this.bExistence = true;
        //           this.TDifferenceDataList = this.initTDifferenceData(res.list);
        //         } else {
        //           var arr = this.searchTDifferenceData();
        //           this.TDifferenceDataList = this.initTDifferenceData(arr);
        //           if (this.TDifferenceDataList.length >= 0) {
        //             this.bValid = true;
        //           }
        //         }
        //       }
        //     }
        //   );
        // }
        // if (this.nType === 4) {
        //   this.getPointRelationSettingsRelationsList(
        //     {
        //       pointId: pointId,
        //       type: 0
        //     },
        //     res => {
        //       if (this.nType === 4) {
        //         if (res && res.length > 0) {
        //           this.bValid = true;
        //           this.bExistence = true;
        //           this.contrastDataList = this.initContrastData(res);
        //         } else {
        //           var arr = this.searchContrastData();
        //           this.contrastDataList = this.initContrastData(arr);
        //           if (this.contrastDataList.length >= 0) {
        //             this.bValid = true;
        //           }
        //         }
        //       }
        //     }
        //   );
        // }
      }
    },
    initTDifferenceData(data) {
      var dataArr = [];
      if (data && data.length > 0) {
        // for (var i = 0, len = data.length; i < len; i++) {}
        dataArr = data.map(item => {
          let relationP =
            item.relationPointIds == ""
              ? []
              : item.relationPointIds.split(",").map(id => {
                  return {
                    pointId: parseInt(id)
                  };
                });
          var filterIds = this.comparedFilter.filter(
            f_item => f_item != relationP[0].pointId
          );
          filterIds.push(item.pointId);
          return {
            pointsList: this.getDevicePointsList(filterIds),
            pointId: item.pointId,
            type: item.type,
            relationPoint:
              item.relationPointIds == ""
                ? []
                : item.relationPointIds.split(",").map(id => {
                    return {
                      pointId: parseInt(id)
                    };
                  })
            // relationPoint:
            //   item.referencePointId == ""
            //     ? []
            //     : (item.referencePointId + "").split(",").map(id => {
            //         return {
            //           pointId: parseInt(id)
            //         };
            //       })
          };
        });
      }
      return dataArr;
    },
    initContrastData(data) {
      var dataArr = [];
      if (data && data.length > 0) {
        dataArr = data.map(item => {
          return {
            pointId: item.pointId,
            type: item.type,
            relationPoint:
              item.relationPointIds == ""
                ? []
                : item.relationPointIds.split(",").map(id => {
                    return {
                      pointId: parseInt(id)
                    };
                  })
            // relationPoint:
            //   item.relationIds == ""
            //     ? []
            //     : item.relationIds.split(",").map(id => {
            //         return {
            //           pointId: parseInt(id)
            //         };
            //       })
          };
        });
      }
      return dataArr;
    },
    searchTDifferenceData() {
      var dataArr = [];
      var arr = this.pointsList.filter(item => {
        return this.formatStr(this.data.name) === this.formatStr(item.name);
      });
      if (arr && arr.length > 0) {
        for (var i = 0, len = arr.length; i < len; i++) {
          var temp = {};
          temp.pointId = arr[i].id;
          temp.type = 1;

          let pointsList = this.getDevicePointsList([arr[i].id]);
          var relationPointIds = "";
          for (var j = 0, j_len = pointsList.length; j < j_len; j++) {
            let p_id = pointsList[j].id;
            if (this.comparedFilter.indexOf(p_id) > -1) {
              //
            } else {
              relationPointIds = p_id;
              break;
            }
          }
          temp.relationPointIds = relationPointIds.toString();
          this.comparedFilter.push(relationPointIds);

          // temp.relationPointIds =
          //   this.getDevicePointsList(arr[i].id).length > 0
          //     ? this.getDevicePointsList(arr[i].id)[0].id.toString()
          //     : "";
          // this.comparedFilter.push(temp.relationPointIds);
          // temp.referencePointId =
          //   this.getDevicePointsList(arr[i].id).length > 0
          //     ? this.getDevicePointsList(arr[i].id)[0].id
          //     : "";
          if (temp.pointId == this.data.id.substring(6, this.data.id.length)) {
            if (dataArr.length > 0) {
              dataArr.unshift(temp);
            } else {
              dataArr.push(temp);
            }
            continue;
          }
          dataArr.push(temp);
        }
      }
      // var relationDataArr = this.searchRelationTDifferenceData(dataArr);
      // return dataArr.concat(relationDataArr);
      return dataArr;
    },
    searchRelationTDifferenceData(data) {
      var dataArr = [];
      if (data && data.length > 0) {
        for (var i = 0, len = data.length; i < len; i++) {
          var arr = data[i].relationPointIds.split(",");
          // var arr = (data[i].referencePointId + "").split(",");
          for (var n = 0, l = arr.length; n < l; n++) {
            dataArr.push({
              pointId: parseInt(arr[n]),
              type: data[i].type,
              relationPointIds: data[i].pointId.toString()
              // referencePointId: data[i].pointId
            });
          }
        }
      }
      return dataArr;
    },
    searchContrastData() {
      var dataArr = [];
      var arr = this.pointsList.filter(item => {
        return this.formatStr(this.data.name) === this.formatStr(item.name);
      });
      if (arr && arr.length > 0) {
        for (var i = 0, len = arr.length; i < len; i++) {
          var temp = {};
          temp.pointId = arr[i].id;
          temp.type = 0;
          temp.relationPointIds = arr
            .filter(item => {
              return item.id != temp.pointId;
            })
            .map(item => {
              return item.id;
            })
            .join(",");
          // temp.relationIds = arr
          //   .filter(item => {
          //     return item.id != temp.pointId;
          //   })
          //   .map(item => {
          //     return item.id;
          //   })
          //   .join(",");
          if (temp.pointId == this.data.id.substring(6, this.data.id.length)) {
            if (dataArr.length > 0) {
              dataArr.unshift(temp);
            } else {
              dataArr.push(temp);
            }
            continue;
          }
          dataArr.push(temp);
        }
      }
      return dataArr;
    },
    formatStr(str) {
      var str = str.replace(/\s+/g, "");
      // var str = str.replace(/[A-Za-z]/g, "");
      var str = str.replace(/[A-C]/g, "-x-x-");
      return str;
    },
    getPointsList() {
      pointsList({ page: 1, size: 0, isDelete: 0 }).then(response => {
        if (response && response.list && response.list.length > 0) {
          this.pointsList = response.list;
          this.setData();
        }
      });
    },
    getDevicePointsList(pointIds) {
      if (pointIds.length <= 0)
        return this.pointsList.filter(item => item.id != "");
      var parentIds = [];
      var dataArr = [];
      if (this.pointsList && this.pointsList.length > 0) {
        for (var i = 0, len = this.pointsList.length; i < len; i++) {
          // if (this.pointsList[i].id === pointId) {
          //   parentId = this.pointsList[i].parentId;
          //   break;
          // }
          if (pointIds.indexOf(this.pointsList[i].id) > -1) {
            parentIds.push(this.pointsList[i].parentId);
          }
        }
        dataArr = this.pointsList.filter(item => {
          return (
            parentIds.indexOf(item.parentId) > -1 &&
            pointIds.indexOf(item.id) <= -1
          );
          // return item.parentId === parentId && item.id !== pointId;
        });
        return dataArr;
      } else {
        return [];
      }
    },
    getPointRelationSettingsList(param, callback) {
      pointRelationSettingsList(param).then(response => {
        if (typeof callback != "undefined") {
          callback(response);
        }
      });
    },
    getPointRelationSettingsRelationsList(param, callback) {
      pointRelationSettingsRelationsList(param).then(response => {
        if (typeof callback != "undefined") {
          callback(response);
        }
      });
    },
    setPointRelationSettingsUpdate(param, bSave) {
      pointRelationSettingsUpdate(param).then(response => {
        if (this.nType === 3) {
          this.setOperationLogs("配置-三相对比");
        } else {
          this.setOperationLogs("配置-三相温差");
        }
        this.$message({
          message: bSave === true ? "绑定成功!" : "解绑成功!",
          type: "success"
        });
        this.$emit("listenToChildEvent", { type: "save" });
        let self = this;
        this.$emit("change", "click");
        self.dialogVisible = false;
        this.dbTableUpdatePub({
          table_id: 1
        });
      });
    },
    saveClick(bSave) {
      var param = {};
      if (this.nType === 3) {
        if (this.TDifferenceDataList && this.TDifferenceDataList.length > 0) {
          param.pointRelationSettingRequests = this.TDifferenceDataList.map(
            item => {
              return {
                pointId: item.pointId,
                type: item.type,
                relationPointIds: bSave
                  ? item.relationPoint
                      .map(it => {
                        return it.pointId;
                      })
                      .join(",")
                  : ""
              };
            }
          );
          for (var i = 0, len = this.TDifferenceDataList.length; i < len; i++) {
            for (
              var n = 0, l = this.TDifferenceDataList[i].relationPoint.length;
              n < l;
              n++
            ) {
              param.pointRelationSettingRequests.push({
                pointId: this.TDifferenceDataList[i].relationPoint[n].pointId,
                type: this.TDifferenceDataList[i].type,
                relationPointIds: bSave
                  ? this.TDifferenceDataList[i].pointId + ""
                  : ""
              });
            }
          }
        }
      }
      if (this.nType === 4) {
        if (this.contrastDataList && this.contrastDataList.length > 0) {
          param.pointRelationSettingRequests = this.contrastDataList.map(
            item => {
              return {
                pointId: item.pointId,
                type: item.type,
                relationPointIds: bSave
                  ? item.relationPoint
                      .map(it => {
                        return it.pointId;
                      })
                      .join(",")
                  : ""
              };
            }
          );
        }
      }
      if (
        param &&
        param.pointRelationSettingRequests &&
        param.pointRelationSettingRequests.length > 0
      ) {
        let tempParam = JSON.parse(JSON.stringify(param));
        param.pointRelationSettingRequests.map(item => {
          item.dependPoint = bSave ? tempParam : "";
        });
        this.setPointRelationSettingsUpdate(param, bSave);
      }
    },
    getRobotParams(data) {
      robotParams(data)
        .then(response => {
          if (response.list && response.list.length > 0) {
            for (var i = 0, len = response.list.length; i < len; i++) {
              if (response.list[i].name === "ros_websocket_ip") {
                this.rosObj.ip = response.list[i].value;
              }
              if (response.list[i].name === "ros_websocket_port") {
                this.rosObj.port = response.list[i].value;
              }
            }
          }
        })
        .catch(() => {});
    },
    // 添加日志管理
    setOperationLogs(content) {
      var parm = {
        content: content,
        deviceId: localStorage.getItem("ydRobot_device_id"),
        type: 0
      };
      postOperationLogs(parm)
        .then(response => {})
        .catch(() => {});
    },
    abcdefa(obj) {
      this.comparedFilter = [];
      this.TDifferenceDataList.forEach(item => {
        if (item.relationPoint.length > 0) {
          this.comparedFilter.push(item.relationPoint[0].pointId);
        }
      });
      this.TDifferenceDataList.forEach(item => {
        var filterIds = this.comparedFilter.filter(
          f_item => f_item != item.relationPoint[0].pointId
        );
        filterIds.push(item.pointId);

        item.pointsList = this.getDevicePointsList(filterIds);
      });
    }
  }
};
</script>

<style>
.PointsEdit {
  /*  */
}
.PointsEdit .el-dialog-redefine {
  width: 60%;
  height: 68%;
  /* margin-top: 10vh !important; */
  /* min-height: 600px; */
}
.PointsEdit .el-dialog__header {
  padding: 0;
  background: linear-gradient(
    rgb(227, 242, 238),
    rgb(202, 231, 238)
  ); /* 标准的语法 */
}
.PointsEdit .el-dialog__header .el-dialog__title {
  line-height: 27px;
  font-size: 14px;
  color: #202123;
  padding: 0 6px;
}
.PointsEdit .el-dialog__header .el-dialog__headerbtn {
  width: 23px;
  height: 23px;
  top: 2px;
  right: 5px;
  font-size: 18px;
  border-radius: 3px;
  border: 1px solid rgb(177, 211, 162);
}
.PointsEdit .el-dialog__body {
  height: calc(100% - 27px);
  padding: 3px;
  background-color: rgb(227, 242, 238);
}
.PointsEdit .outside-border {
  width: 100%;
  height: 100%;
  padding: 6px 8px;
  border: 1px solid rgb(194, 221, 228);
  background-color: #ffffff;
}
.PointsEdit .data-area {
  position: relative;
  width: 100%;
  height: calc(100% - 50px);
  border: 1px solid rgb(202, 231, 238);
}

.PointsEdit .el-tabs-redefine {
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: column;
}

.PointsEdit .el-tabs__header {
  box-sizing: border-box;
  background: linear-gradient(
    rgb(227, 242, 238),
    rgb(202, 231, 238)
  ); /* 标准的语法 */
}

.PointsEdit .el-tabs--border-card {
  border: none;
}

.PointsEdit .el-tabs--border-card > .el-tabs__content {
  flex-grow: 1;
  padding: 8px 8px 8px 8px;
}

.PointsEdit .el-tabs--border-card > .el-tabs__header .el-tabs__item {
  height: 30px;
  margin: 0px 3px 0px 3px;
  line-height: 30px;
  border: 1px solid #ccc;
  border-bottom: none;
  border-radius: 4px 4px 0 0;
  color: #000;
}

.PointsEdit .el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active {
  color: rgb(16, 156, 180);
  border: 1px solid rgb(16, 156, 180);
  border-bottom: none;
}

.PointsEdit .el-tab-pane {
  width: 100%;
  height: 100%;
}

.PointsEdit .tab-custom-area {
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: column;
}

.PointsEdit .conditions-area {
  width: 100%;
  height: auto;
  border: 1px solid rgb(186, 232, 247);
  padding-top: 16px;
  padding-right: 16px;
  overflow: auto;
}
.PointsEdit .el-form-item--mini.el-form-item {
  margin-top: 0;
  margin-bottom: 16px;
}
.PointsEdit .tip-info {
  width: 100%;
  height: 36px;
  line-height: 36px;
  text-align: center;
  font-size: 17px;
  color: #ff0000;
}
</style>